//
//  InputPupilInfoViewController.m
//  ConghuiEducation
//
//  Created by leo on 16/9/1.
//  Copyright © 2016年 sample. All rights reserved.
//

#import "InputPupilInfoViewController.h"
#import "ImageMagickTools.h"
#import "GradeClassSelectViewController.h"


@interface InputPupilInfoViewController ()

@end

@implementation InputPupilInfoViewController
@synthesize _tableView;
@synthesize avatarButton;
@synthesize nameTextField;
@synthesize fatherNameTextField;
@synthesize classButton;
@synthesize gradeButton;
@synthesize phoneNumberTextField;
@synthesize addressTextField;
@synthesize dinner_fee_switch;
@synthesize guideWord_fee_switch;
@synthesize pupil;
@synthesize isNewPupil;


- (void)viewDidLoad {
    self.title = @"录入学生档案";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHeightChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(0, 0, 45, 35)];
    [backButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = cancel;
    
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveButton setFrame:CGRectMake(0, 0, 45, 35)];
    [saveButton addTarget:self action:@selector(saveButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = save;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)cancelButtonClick:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)saveButtonClick:(id)sender{
    //判断是否选择了
    if(nameTextField.text == nil || [[nameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
        [self showError:@"请输入姓名" closeInterval:2.0 afterShow:nil];
        return;
    }
    if(fatherNameTextField.text == nil || [[fatherNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
        [self showError:@"输入监护人姓名" closeInterval:2.0 afterShow:nil];
        return;
    }
    if(phoneNumberTextField.text == nil || [[phoneNumberTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
        [self showError:@"请输入手机号" closeInterval:2.0 afterShow:nil];
        return;
    }
    if(addressTextField.text == nil || [[addressTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
        [self showError:@"请输入地址" closeInterval:2.0 afterShow:nil];
        return;
    }
    //保存了
    if(isNewPupil){
        NSInteger pupilid = [[CoreDataManager sharedManager] getNewPupilID];
        [[CoreDataManager sharedManager] saveNewPupilWithDic:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:pupilid],@"pupil_id",nameTextField.text,@"name",fatherNameTextField.text,@"father_name",phoneNumberTextField.text,@"phone_number",addressTextField.text,@"address", nil]];
        NSLog(@"保存成功了");
    }
}

-(IBAction)gradeButtonClick{
    GradeClassSelectViewController *grade = [[GradeClassSelectViewController alloc] initWithNibName:@"GradeClassSelectViewController" bundle:nil];
    [grade setType:0];
    UIPopoverController *popViewController = [[UIPopoverController alloc] initWithContentViewController:grade];
    [popViewController setDelegate:self];
    [popViewController setPopoverContentSize:CGSizeMake(200,150)];
    [popViewController presentPopoverFromRect:CGRectMake(10, 10, 50, 50)
                                       inView:self.view
                     permittedArrowDirections:UIPopoverArrowDirectionRight
                                     animated:YES];
}
-(IBAction)classButtonClick{
    GradeClassSelectViewController *grade = [[GradeClassSelectViewController alloc] initWithNibName:@"GradeClassSelectViewController" bundle:nil];
    [grade setType:1];
    UIPopoverController *popViewController = [[UIPopoverController alloc] initWithContentViewController:grade];
    [popViewController setDelegate:self];
    [popViewController setPopoverContentSize:CGSizeMake(200,150)];
    [popViewController presentPopoverFromRect:CGRectMake(10, 10, 50, 50)
                                       inView:self.view
                     permittedArrowDirections:UIPopoverArrowDirectionRight
                                     animated:YES];
}

-(IBAction)avatarButtonClick{
    TangyuanSheet *sheet = [[TangyuanSheet alloc]initWithTitle:@"更改头像" withCancelstr:@"取消"];
    [sheet addButtonWithTitle:@"拍照" withTitleColor:nil withIcon:nil withHighIcon:nil block:^(void){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.allowsEditing = YES;
            [picker setDelegate:self];
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    
    [sheet addButtonWithTitle:@"从相册选择" withTitleColor:nil withIcon:nil withHighIcon:nil block:^(void){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        [picker setDelegate:self];
        
        UIPopoverController *popViewController = [[UIPopoverController alloc] initWithContentViewController:picker];
        [popViewController setDelegate:self];
        [popViewController setPopoverContentSize:CGSizeMake(200,150)];
        [popViewController presentPopoverFromRect:CGRectMake(10, 10, 50, 50)
                                           inView:self.view
                         permittedArrowDirections:UIPopoverArrowDirectionRight
                                         animated:YES];
        
        //[self presentViewController:picker animated:YES completion:nil];
    }];
    
    [sheet showInView:nil];
}

#pragma mark- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [self dismissViewControllerAnimated:YES
                             completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"图片选择成功，开始上传并更新之前图片%@",info);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    NSString *resource = [NSString stringWithFormat:@"%@/avatar_1.jpg",documentDir];
    
    [ImageMagickTools compress:[info objectForKey:UIImagePickerControllerEditedImage] path:resource];
    BOOL flag = [fileManager fileExistsAtPath:resource];
    if(flag == YES){
        NSLog(@"***************");
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:resource,@"avatar", nil];
    }else{
        NSLog(@"---------------");
    }
    
    [self dismissViewControllerAnimated:YES
                             completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES
                             completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [viewController.navigationItem setTitle:@"选择图片"];
}

#pragma mark- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 88;
    }else{
        return 60;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //头像姓名  父亲姓名电话地址 年级班级  缴费信息（小饭桌 作业辅导）
    if(section == 0){
        return 1;
    }else if(section == 1){
        return 3;
    }else if(section == 2){
        return 2;
    }else if(section == 3){
        return 2;
    }
    return 0;
}


#pragma mark- UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier1 = [NSString stringWithFormat:@"%d_%d",indexPath.section,indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        if(indexPath.section == 0){
            cell.textLabel.text = @"";
            
            [avatarButton setFrame:CGRectMake(20, 88/2-60/2, 60, 60)];
            [[cell contentView] addSubview:avatarButton];
            
            [nameTextField setFrame:CGRectMake(20+60+30, 88/2-20, KScreenWidth-120, 40)];
            [[cell contentView] addSubview:nameTextField];
        }else if(indexPath.section == 1){
            if(indexPath.row == 0){
                cell.textLabel.text = @"监护人";
                [fatherNameTextField setFrame:CGRectMake(20+60+30, 60/2-20, KScreenWidth-120, 40)];
                [[cell contentView] addSubview:fatherNameTextField];
            }else if(indexPath.row == 1){
                cell.textLabel.text = @"手机号";
                [phoneNumberTextField setFrame:CGRectMake(20+60+30, 60/2-20, KScreenWidth-120, 40)];
                [[cell contentView] addSubview:phoneNumberTextField];
            }else if(indexPath.row == 2){
                cell.textLabel.text = @"家庭住址";
                [addressTextField setFrame:CGRectMake(20+60+30, 60/2-20, KScreenWidth-120, 40)];
                [[cell contentView] addSubview:addressTextField];
            }
        }else if(indexPath.section == 2){
            if(indexPath.row == 0){
                cell.textLabel.text = @"年级";
                
                [gradeButton setFrame:CGRectMake(20+60+30, 60/2-20, KScreenWidth-120, 40)];
                [[cell contentView] addSubview:gradeButton];
            }else if(indexPath.row == 1){
                cell.textLabel.text = @"班级";
                
                [classButton setFrame:CGRectMake(20+60+30, 60/2-20, KScreenWidth-120, 40)];
                [[cell contentView] addSubview:classButton];
            }
        }else if(indexPath.section == 3){
            if(indexPath.row == 0){
                cell.textLabel.text = @"小饭桌缴费";
                
                [dinner_fee_switch setFrame:CGRectMake(KScreenWidth-51-30, 60/2-31/2, 51, 31)];
                [[cell contentView] addSubview:dinner_fee_switch];
            }else if(indexPath.row == 1){
                cell.textLabel.text = @"辅导班缴费";
                
                [guideWord_fee_switch setFrame:CGRectMake(KScreenWidth-51-30, 60/2-31/2, 51, 31)];
                [[cell contentView] addSubview:guideWord_fee_switch];
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    

}



#pragma mark-
-(void)keyboardHeightChange:(NSNotification *)noti{
    
}

-(void)keyboardWillShow:(NSNotification *)noti{
    NSDictionary* info = [noti userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到键盘的高度
    [UIView animateWithDuration:0.3 animations:^(void){
        [_tableView setFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-kbSize.height)];
    }completion:^(BOOL finished){
        
    }];
    
}

-(void)keyboardDidShow:(NSNotification *)noti{
    
}

-(void)keyboardWillHide:(NSNotification *)noti{
    [UIView animateWithDuration:0.3 animations:^(void){
        [_tableView setFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    }completion:^(BOOL finished){
        
    }];
}

@end
